/* ****************************************************************************
 * Author: 671643387
 * Date: 2015/3/17
 * ***************************************************************************/

Date.prototype.format = function(fmt)
{ //author: meizz
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
};

Ext.Loader.setConfig({
    disableCaching: false
});

Ext.application({
    name: "sggm",
    autoCreateViewport: true,

    requires: [
        'sggm.utils.Common',
        'sggm.utils.Cookie',
        'sggm.utils.Http'
    ],

    controllers: [
        'GMPanel',
        'ContentLeft',
        'MainFrame'
    ],

    models: [
        'UserInfo',
        'UserStatus',
        'UserMark',
        'UserSoldier',
        'UserInventory',
        'Message'
    ],

    stores: [
        'UserInfo',
        'UserStatus',
        'UserMark',
        'UserSoldier',
        'UserInventory',
        'Message'
    ],

    sgConfigs: {
        "role": {},
        "material": {},
        "gem": {}
    },

    userPrivilege: -1,
    modelPrivileges: null,
    playerData:null,

    launch: function() {
        console.log("APP Launching...");

        var me = this;
        var href=location.href;
        sggm.utils.Http.url = href.substr(0, href.lastIndexOf('/')) + '/';
        sggm.utils.Http.app = me;

        var authKey = sggm.utils.Common.getAuthKey();
        if (authKey && this.parseCachedData()) {
            this.loadConfigs(function(sus){
                if (sus) {
                    me.showGMTools();
                } else {
                    Ext.MessageBox.alert("提示", "加载配置文件错误，请联系管理员");
                }
            });
        } else {
            this.reLogin();
        }
    },

    logout: function() {
        sggm.utils.Cookie.set("sggmCachedObj", undefined);
        this.reLogin();
    },

    parseCachedData: function() {
        var cachedObj = null;
        var cachedStr = sggm.utils.Cookie.get("sggmCachedObj");
        if (cachedStr) {
            try { cachedObj = JSON.parse(cachedStr); } catch(e) {}
            if (cachedObj) {
                this.userPrivilege = cachedObj["userPrivilege"] || -1;
                this.modelPrivileges = cachedObj["modelPrivileges"] || null;
                return (this.modelPrivileges != null && this.userPrivilege != -1);
            }
        }
        return false;
    },

    cacheData: function(key, obj) {
        var cachedObj = null;
        var cachedStr = sggm.utils.Cookie.get("sggmCachedObj");
        if (cachedStr) {
            try { cachedObj = JSON.parse(cachedStr); } catch(e) {}
        }
        cachedObj = cachedObj || {};
        cachedObj[key] = obj;
        sggm.utils.Cookie.set("sggmCachedObj", JSON.stringify(cachedObj));
    },


    /**
     * 用户登录
     * @param cb 登录成功回调
     * @param scope 回调函数执行上下文
     */
    login: function(cb, scope) {
        var me = this;
        var loginWindow = null;
        var loginForm = null;
        Ext.createWidget("loginWindow", {
            onLogin: function(win, form){
                loginWindow = win;
                loginForm = form;


                loginWindow.hide();
                sggm.utils.Http.request({
                    act: "gm_login",
                    params: form.getForm().getValues()
                }, function(res){
                    if (res["code"] == 0) {
                        // 登录成功
                        sggm.utils.Http.authKey = res["data"]["authKey"];
                        sggm.utils.Http.authGM = res["data"]["account"];
                        sggm.utils.Cookie.set("authKeyXB", res["data"]["authKey"]);
                        sggm.utils.Cookie.set("authGM", res["data"]["account"]);
                        me.userPrivilege = res["data"]["privilege"];
                        me.modelPrivileges = res["data"]["modPrivileges"];
                        me.cacheData("userPrivilege", me.userPrivilege);
                        me.cacheData("modelPrivileges", me.modelPrivileges);

                        cb.call(scope);
                    } else {
                        loginWindow.show();
                    }
                }, function(){
                    loginWindow.show();
                });
            }
        }).show();
    },

    reLogin: function() {
        var me = this;
        var rootView = Ext.getCmp("rootView");
        rootView.removeAll(true);
        this.login(function(){
            console.log("登录成功");
            this.loadConfigs(function(sus){
                if (sus) {
                    me.showGMTools();
                } else {
                    Ext.MessageBox.alert("提示", "加载配置文件错误，请联系管理员");
                }
            });
        }, this);
    },

    showGMTools: function() {
        var rootView = Ext.getCmp("rootView");
        //rootView.add({xtype: "gmPanel"});
        rootView.add({xtype: "mainFrame"});
    },

    loadConfigs: function(callback) {
        var loadMask = new Ext.LoadMask(Ext.getBody(), {
            msg: "正在加载配置，请稍等...",
            removeMask: true
        });
        loadMask.show();

        var counter = 3;
        var loadConfigSus = true;
        function onConfigLoad(sus) {
            if (!sus) loadConfigSus = false;
            counter = counter-1;
            if (counter <= 0) {
                loadMask.hide();
                callback(loadConfigSus);
            }
        }

        this.loadConfig("conf/role.dat", this.sgConfigs.role, onConfigLoad);
        this.loadConfig("conf/material.dat", this.sgConfigs.material, onConfigLoad);
        this.loadConfig("conf/gem.dat", this.sgConfigs.gem, onConfigLoad);
    },

    loadConfig: function(file, confObj, callback) {
        sggm.utils.Http.requestFile({
            file: file
        }, function(content){
            var lines = content.split("\n");
            var cols = lines[1].split("\t");
            for( var i=2; i<lines.length; i++ ) {
                var line = lines[i].split("\t");
                if( line.length != cols.length ) continue;
                var lineObj = {};
                for( var j=0; j<line.length; j++ ) {
                    lineObj[cols[j]] = line[j];
                }
                confObj[lineObj.Id] = lineObj;
            }
            callback(true);
        }, function(){
            callback(false);
        });
    },

    /**
     * 检查用户是否有权限访问某个资源
     * @param act
     */
    checkAccess: function(act){
        if (this.userPrivilege <= 0) {
            return false;
        }
        if (!this.modelPrivileges) {
            return false;
        }
        var modAct = "gm:" + act;
        var modActPrivilege = this.modelPrivileges[modAct];
        if (!modActPrivilege) return false;
        var allowList = modActPrivilege["allowplevel"];
        return allowList.hasOwnProperty(this.userPrivilege);
    }
});
